package com.ewanghuiju.app.util;

import android.content.ContentValues;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

import com.ewanghuiju.app.R;
import com.ewanghuiju.app.app.Constants;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.tools.DateUtils;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.luck.picture.lib.tools.SdkVersionUtils;
import com.luck.picture.lib.tools.ValueOf;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author sj  qq:751943509
 * @class describe
 * @time 2020/2/27
 */
public class StringUtil {
    public final static String MIME_TYPE_IMAGE = "image/jpeg";
    public final static String MIME_TYPE_VIDEO = "video/mp4";
    public final static String MIME_TYPE_AUDIO = "audio/mpeg";

    /**
     * 获取一定数量的空字符串
     *
     * @return
     */
    public static String getKongStrBynum(String text) {
        if (TextUtils.isEmpty(text)) {
            return "\u3000\u3000";
        }
        int num = text.length();
        String str = "\u3000\u3000";
        if (num <= 2) {
            return str;
        }
        for (int i = 0; i < num - 2; i++) {
            str += " ";
        }
        return str;
    }


    public static void getTextStrFormat(TextView tv, String str, String text) {
        if (TextUtils.isEmpty(str)) {
            tv.setText(TextUtils.isEmpty(text) ? "" : text);
            return;
        }
        SpannableStringBuilder span = new SpannableStringBuilder(str + text);
        span.setSpan(new ForegroundColorSpan(Color.TRANSPARENT), 0, str.length(),
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(span);
    }

    /**
     * 隐藏手机号
     *
     * @param phone
     * @return
     */
    public static String getFormatePhone(String phone) {
        if (TextUtils.isEmpty(phone)) {
            return "";
        }
        if (phone.length() < 11) {
            return phone;
        }
        return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    /**
     * 获取相应位数的字符 ， 超过用...
     *
     * @param text
     * @return
     */
    public static String getLengthTextByStr(String text, int length) {
        if (TextUtils.isEmpty(text)) {
            return "";
        }
        if (text.length() > length) {
            return text.substring(0, length) + "...";
        }
        return text;
    }

    /**
     * 是否是6位数字
     *
     * @param str
     * @return
     */
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]{6}$");
        return pattern.matcher(str).matches();
    }

    /**
     * 是否是手机号
     *
     * @param value
     * @return
     */
    public static boolean isPhone(String value) {
        if (value != null && value.length() == 11) {
            Pattern pattern = Pattern.compile("^1[3|4|5|6|7|8|9][0-9]\\d{8}$");
            Matcher matcher = pattern.matcher(value);
            return matcher.matches();
        }
        return false;
    }

    /**
     * str 是否大于0
     *
     * @param str
     * @return
     */
    public static boolean isMoreThan(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        try {
            float mFloat = Float.parseFloat(str);
            return mFloat > 0;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断字符串是否是金额
     *
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
        java.util.regex.Matcher match = pattern.matcher(str);
        if (match.matches() == false) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 倒计时转化
     *
     * @param l
     * @return
     */
    public static String getTimeStr(long l) {
        long day = l / (1000 * 24 * 60 * 60); //单位天
        long hour = (l - day * (1000 * 24 * 60 * 60)) / (1000 * 60 * 60); //单位时
        long minute = (l - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60)) / (1000 * 60); //单位分
        long second = (l - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000;//单位秒

        String hourStr = String.valueOf(hour);
        if (hourStr.length() == 1) {
            hourStr = "0" + hourStr;
        }
        String minStr = String.valueOf(minute);
        if (minStr.length() == 1) {
            minStr = "0" + minStr;
        }
        String secondStr = String.valueOf(second);
        if (secondStr.length() == 1) {
            secondStr = "0" + secondStr;
        }
        //如果day为0的时候天不显示
        if (day == 0) {
            return hourStr + ":" + minStr + ":" + secondStr;
        } else {
            return day + "天" + " " + hourStr + ":" + minStr + ":" + secondStr;
        }
    }

    /**
     * 字符串以逗号分隔返回数组
     *
     * @param str
     * @return
     */
    public static List<String> getStringListBySplit(String str) {
        List<String> mList = new ArrayList<>();
        if (TextUtils.isEmpty(str)) {
            return mList;
        }
        String[] strArr = str.split(",");
        if (strArr != null && strArr.length > 0) {
            for (int i = 0; i < strArr.length; i++) {
                mList.add(strArr[i]);
            }
        }
        return mList;

    }

    /**
     * 下载图片保存至手机
     *
     * @param urlPath
     */
    public static void showLoadingImage(String urlPath, Handler mHandler, Context mContext) {
        BufferedOutputStream bout = null;
        Uri outImageUri = null;
        try {
            String currentMimeType = PictureMimeType.getImageMimeType(urlPath);
            String mMimeType = PictureMimeType.isJPG(currentMimeType) ? PictureMimeType.MIME_TYPE_JPEG : currentMimeType;
            URL u = new URL(urlPath);
            String path;
            if (SdkVersionUtils.checkedAndroid_Q()) {
                outImageUri = createOutImageUri(mContext, mMimeType);
                if (outImageUri == null) {
                    mHandler.sendEmptyMessage(Constants.SAVE_IMAGE_ERROR);
                    return;
                }
                bout = new BufferedOutputStream(mContext.getContentResolver().openOutputStream(outImageUri));
                path = PictureFileUtils.getPath(mContext, outImageUri);
            } else {
                String suffix = PictureMimeType.getLastImgSuffix(mMimeType);
                String state = Environment.getExternalStorageState();
                File rootDir =
                        state.equals(Environment.MEDIA_MOUNTED)
                                ? Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                                : mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                if (rootDir != null && !rootDir.exists() && rootDir.mkdirs()) {
                }
                File folderDir = new File(!state.equals(Environment.MEDIA_MOUNTED)
                        ? rootDir.getAbsolutePath() : rootDir.getAbsolutePath() + File.separator + "Camera" + File.separator);
                if (folderDir != null && !folderDir.exists() && folderDir.mkdirs()) {
                }
                String fileName = DateUtils.getCreateFileName("IMG_") + suffix;
                File file = new File(folderDir, fileName);
                path = file.getAbsolutePath();
                bout = new BufferedOutputStream(new FileOutputStream(path));
            }
            if (bout == null) {
                mHandler.sendEmptyMessage(Constants.SAVE_IMAGE_ERROR);
                return;
            }
            byte[] buffer = new byte[1024 * 8];
            int read;
            int ava = 0;
            long start = System.currentTimeMillis();
            BufferedInputStream bin = new BufferedInputStream(u.openStream());
            while ((read = bin.read(buffer)) > -1) {
                bout.write(buffer, 0, read);
                ava += read;
                long speed = ava / (System.currentTimeMillis() - start);
            }
            bout.flush();
            Message message = mHandler.obtainMessage();
            message.what = Constants.SAVE_IMAGE_SUCCESSFUL;
            message.obj = path;
            mHandler.sendMessage(message);
        } catch (IOException e) {
            mHandler.sendEmptyMessage(Constants.SAVE_IMAGE_ERROR);
            if (outImageUri != null) {
                mContext.getContentResolver().delete(outImageUri, null, null);
            }
            e.printStackTrace();
        } finally {
            try {
                if (bout != null) {
                    bout.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 针对Q版本创建uri
     *
     * @return
     */
    private static Uri createOutImageUri(Context mContext, String mMimeType) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, DateUtils.getCreateFileName("IMG_"));
        contentValues.put(MediaStore.Images.Media.DATE_TAKEN, ValueOf.toString(System.currentTimeMillis()));
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, mMimeType);
//        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, PictureMimeType.DCIM);

        return mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
    }

    /**
     * 根据 type 获取会员级别       //会员级别 0: 普通 1:团长 2:代理 3: 区域代理 4: 销售
     *
     * @return
     */
    public static String getDailiInfo(int type) {
        if (type == 0) {
            return "普通会员";
        } else if (type == 1) {
            return "团长";
        } else if (type == 2) {
            return "代理";
        } else if (type == 3) {
            return "区域代理";
        } else if (type == 4) {
            return "销售";
        }
        return "";
    }

    /**
     * 根据string转化成int
     *
     * @param string
     * @return
     */
    public static int getNumberByString(String string) {
        if (TextUtils.isEmpty(string)) {
            return 0;
        }
        try {
            return Integer.parseInt(string);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return 0;
        }

    }

    /**
     * 根据string转化成float
     *
     * @param string
     * @return
     */
    public static float getFloatByString(String string) {
        if (TextUtils.isEmpty(string)) {
            return 0L;
        }
        try {
            return Float.parseFloat(string);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return 0L;
        }

    }

    /**
     * 获取类型   ---图片 gif  视频  音频
     *
     * @param name
     * @return
     */
    public static String getMimeType(String name) {
        if (!TextUtils.isEmpty(name)) {
            if (name.endsWith(".mp4") || name.endsWith(".avi")
                    || name.endsWith(".3gpp") || name.endsWith(".3gp") || name.endsWith(".mov")) {
                return MIME_TYPE_VIDEO;
            } else if (name.endsWith(".PNG") || name.endsWith(".png") || name.endsWith(".jpeg")
                    || name.endsWith(".gif") || name.endsWith(".GIF") || name.endsWith(".jpg")
                    || name.endsWith(".webp") || name.endsWith(".WEBP") || name.endsWith(".JPEG")
                    || name.endsWith(".bmp")) {
                return MIME_TYPE_IMAGE;
            } else if (name.endsWith(".mp3") || name.endsWith(".amr")
                    || name.endsWith(".aac") || name.endsWith(".war")
                    || name.endsWith(".flac") || name.endsWith(".lamr")) {
                return MIME_TYPE_AUDIO;
            }
        }
        return MIME_TYPE_IMAGE;
    }

    /**
     * 判断是否是gif
     *
     * @param name
     * @return
     */
    public static boolean getMimeTypeIsGif(String name) {
        if (!TextUtils.isEmpty(name)) {
            if (name.endsWith(".gif") || name.endsWith(".GIF")) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 根据位置 获取类型
     *
     * @param position
     * @return
     */
    public static int getOrderTypeBy(int position) {
        if (position == 6) {
            return 3;
        } else if (position >= 3 && position < 6) {
            return position + 1;
        } else {
            return position;
        }
    }

    /**
     * 数量转化
     *
     * @param num
     * @return
     */
    public static void getTipByNum(TextView mTextView,int num) {
        String numStr = num+"";
        if (numStr.length() > 1) {
            mTextView.setBackgroundResource(R.drawable.corner_primary_radiu_7_stroke_1);
        }else{
            mTextView.setBackgroundResource(R.drawable.corner_oval_primary_stroke_1);
        }
        mTextView.setText(numStr);
    }
}
